package com.moore.service.Impl;

import com.moore.bean.Contract;
import com.moore.bean.Message;
import com.moore.dto.ResponseData;
import com.moore.mapper.ContractMapper;
import com.moore.service.ContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.sql.Date;
import java.util.List;

@Service
public class ContractServiceImpl implements ContractService {
    @Autowired
    private ContractMapper contractMapper;
    @Override
    public ResponseData getContractInfo(String account) {
        int result = contractMapper.getContract(account);
        if (result == 0) {
            Contract contractInfo = contractMapper.getContractInfo(account);
            return new ResponseData(200, "查询成功", contractInfo, 1);
        } else {
            return new ResponseData(500, "合同已签署，无需重复签署！", null, 0);
        }
    }

    @Override
    public ResponseData signContract(Contract contract) {
        int result = contractMapper.confirmPassword(contract.getTenantId(),contract.getPassword());
        if (result == 0) {
            return new ResponseData(200,"密码不正确，请重试",null,0);
        }
        int result1 = contractMapper.addContract(contract);
        int result2 = contractMapper.updateStatusToRented((int) contract.getTenantId());
        if (result1 == 1 && result2 >0) {
            return new ResponseData(200,"签署成功！",null,0);
        } else {
            return new ResponseData(500,"签署失败！",null,0);
        }
    }

    @Override
    public ResponseData getContractList(Date startDate, Date endDate, String name, String status, int curr, int size, HttpServletRequest request) {
        List<Contract> contracts = contractMapper.getContractList(startDate,endDate,name,status,curr,size);
        String serverUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        for(Contract contract:contracts){
            contract.setAutograph(serverUrl + contract.getAutograph());
        }
        return new ResponseData(200,"查询成功", contracts, contractMapper.getContractCount(startDate,endDate,name,status));
    }

    @Override
    public ResponseData terminationContract(int id, String name, String msg) {
        int result = contractMapper.terminationContract(id);
        Message message = new Message(contractMapper.getTenant(name),
                "解约",
                "合同解约通知",
                "尊敬的"+name+"，很抱歉通知您，您的合同由于"+msg+"原因被解约，" +
                        "请于5日内搬离房屋，否则我司有权对房屋进行清理，并确保房屋水电设施完好，" +
                        "否则需照价赔偿，特此通知！","资质审核员","未读");
        int result2 = contractMapper.sendMessage(message);
        if (result > 0 && result2 > 0) return new ResponseData(200,"解约成功",null,0);
        else return new ResponseData(500,"解约失败",null,0);
    }
}
